import sensor, image, display, time, gt911
from pyb import Timer, Pin

sensor.reset() # 初始化sensor
sensor.set_pixformat(sensor.RGB565) # or sensor.GRAYSCALE
sensor.set_framesize(sensor.QVGA) # 320*240大小的液晶屏

# gt911的初始化必须放在屏幕初始化前
gt911.init(bus = 4,axis = 0)
# 初始化lcd屏幕，lcdtype = 0为2.0寸屏幕，lcdtype = 1为2.8寸屏幕
lcd = display.SPIDisplay(width = 320, height = 240, lcdtype = 1)

light = 0
tim2 = Timer(2, freq = 1000)
ch = tim2.channel(1, Timer.PWM, pin = Pin("P6"))
ch.pulse_width_percent(light)

while(True):
    img = sensor.snapshot().lens_corr(strength = 1.8, zoom = 1.0)
    n, points = gt911.read_points()
    for i in range(0, n):
        x = points[i][0]
        y = points[i][1]
        size = points[i][2]
        img.draw_circle(x, y, 2, color = (255, 0, 0), fill = True)
        print(f"id {points[i][3]} x {x} y {y} size {size}")
        if(x > 10 and x < 60 and y > 10 and y < 35):
            light = 100
            ch.pulse_width_percent(light)
            x = 0
            y = 0
        elif(x > 10 and x < 60 and y > 60 and y < 85):
            light = 0
            ch.pulse_width_percent(light)
            x = 0
            y = 0
        elif(x > 70 and x < 120 and y > 10 and y < 35):
            if(light<100):
                light = light + 5
            ch.pulse_width_percent(light)
            x = 0
            y = 0
        elif(x > 70 and x < 120 and y > 60 and y < 85):
            if(light>0):
                light = light - 5
            ch.pulse_width_percent(light)
            x = 0
            y = 0
    img.draw_rectangle((10,10,50,25))
    img.draw_string(18, 10, "Open", scale = 2, color=(255,0,0), mono_space = False)
    img.draw_rectangle((10,60,50,25))
    img.draw_string(18, 60, "Close", scale = 2, color=(255,0,0), mono_space = False)

    img.draw_rectangle((70,10,50,25))
    img.draw_string(78, 10, "Add", scale = 2, color=(255,0,0), mono_space = False)
    img.draw_rectangle((70,60,50,25))
    img.draw_string(78, 60, "Minus", scale = 2, color=(255,0,0), mono_space = False)

    img.draw_string(10, 100, "light:%d" % light, scale = 2, color=(255,0,0), mono_space = False)
    lcd.write(img) # 拍照并显示图像


